package com.my.study.structures.stack;

/**
 * @author Carlos
 * @version 1.0
 * @Description 利用栈实现计算器功能
 * @date 2021/6/22 21:48
 **/
public class Calculator {

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append("ss");
        System.out.println(sb.toString());

        sb.setLength(0);
        System.out.println(sb.toString());

//        String expression = "31+2*6-20";
//        cal(expression);
    }

    private static void cal(String expression) {
        ArrayStack numStack = new ArrayStack(5);
        ArrayStack operStack = new ArrayStack(3);
        // 定义相关需要的变量
        int index = 0, num1 = 0, num2 = 0, oper = 0;
        int result = 0;
        char ch = ' ';
        StringBuilder keepNum = new StringBuilder();
        while (index <= expression.length() - 1) {
            ch = expression.charAt(index);
            // 判断ch是否为符号
            if (operStack.isOper(ch)) {
                // 符号栈不为空
                if (!operStack.isEmpty()) {
                    // 1.当前运算符号的优先级<=符号栈栈顶的符号优先级，则使用栈顶符号进行运算
                    if (operStack.priority(ch) <= operStack.priority(operStack.peek())) {
                        num1 = numStack.pop();
                        num2 = numStack.pop();
                        oper = operStack.pop();
                        result = numStack.cal(num1, num2, oper);

                        numStack.push(result);
                        operStack.push(ch);
                    }
                    // 2.当前运算符号的优先级>=符号栈栈顶的符号优先级，则使用当前符号入栈
                    else {
                        operStack.push(ch);
                    }
                }
                // 符号栈为空
                else {
                    operStack.push(ch);
                }
            }
            // 为数字
            else {
                keepNum.append(ch);
                if (index == expression.length() - 1) {
                    numStack.push(Integer.parseInt(keepNum.toString()));
                } else {
                    if (operStack.isOper(expression.charAt(index + 1))) {
                        numStack.push(Integer.parseInt(keepNum.toString()));
                        keepNum.setLength(0);
                    }
                }
            }
            index++;
        }

        while (!operStack.isEmpty()) {
            num1 = numStack.pop();
            num2 = numStack.pop();
            oper = operStack.pop();
            result = numStack.cal(num1, num2, oper);

            numStack.push(result);
        }

        System.out.printf("表达式%s = %d", expression, numStack.pop());
    }

}
